# @Author: Yao Heng Hui
#-*- coding: utf-8 -*-
import smtplib
import email
import os
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from bs4 import BeautifulSoup


class SendMail(object):  # 设置smtplib所需的参数
    def __init__(self):
        self.smtpserver = 'smtp.exmail.qq.com'  # SMTP服务器地址
        self.username = 'itsupport@mcpsystem.com'  # 发件人地址，通过控制台创建的发件人地址
        self.password = 'Mw1234567'  # 发件人密码，通过控制台创建的发件人密码
        self.success_receivers = ['yaohenghui@mwclg.com', 'zongw@mwclg.com', 'zhangsq@mwclg.com', 'yangys@mwclg.com']  # 用例成功收件人,最多支持30个
        self.fail_receivers = ['yaohenghui@mwclg.com', 'zongw@mwclg.com', 'zhangsq@mwclg.com', 'yangys@mwclg.com']  # 用例失败收件人，最多支持30个
        self.receivers = []
        # self.report_file = report_file

    def build_email(self, report_file):
        # 构造邮件MIMEMultipart对象
        report_file = report_file
        msg = MIMEMultipart('mixed')
        msg['Subject'] = Header('自动化测试报告' + time.strftime("%Y-%m-%d"), 'utf-8').encode()  # 自定义邮件主题
        msg['From'] = '%s <%s>' % (self.username, self.username)  # 邮件发送者
        # 构造邮件信息
        sendfile = open(report_file, 'rb').read()
        text_att = MIMEText(sendfile, 'base64', 'utf-8')
        text_att["Content-Type"] = 'application/octet-stream'
        text_att["Content-Disposition"] = 'attachment; filename="report.html"'  # 重新命名附件
        msg.attach(text_att)
        with open(report_file, encoding='utf-8') as fp:
            f = fp.read()
        soup = BeautifulSoup(f, 'lxml')
        status = soup.find_all(class_='attribute')
        result = status[2].contents[-6:]
        content = '运行结果：'
        is_result_pass = True
        for i in result:
            param = i.string
            content = content + param
            if 'Error' in i:
                is_result_pass = False
        if is_result_pass:
            text_plain = MIMEText('测试通过，附件为接口自动化测试报告，请查收！', 'plain', 'utf-8')  # 邮件内容
            msg.attach(text_plain)
            self.receivers = self.success_receivers
        else:
            text_plain = MIMEText(content + '\n' + '测试不通过，附件为接口自动化测试报告，请查收！', 'plain', 'utf-8')  # 邮件内容
            msg.attach(text_plain)
            self.receivers = self.fail_receivers

        msg['To'] = ";".join(self.receivers)  # 邮件接受者
        # 发送邮件
        # client = smtplib.SMTP()
        # client.connect(smtpserver, 25) #SMTP普通端口为25
        client = smtplib.SMTP_SSL(host='smtp.exmail.qq.com')  # python 2.7以上版本，若需要可使用SSL
        client.connect(self.smtpserver, 465)  # SSL端口465

        # client.set_debuglevel(1) #用set_debuglevel(1)可以打印出和SMTP服务器交互的所有信息
        client.login(self.username, self.password)
        client.sendmail(self.username, self.success_receivers, msg.as_string())
        client.quit()
